<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0, user-scalable=no">
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14"></script>
</head>
  <body>
      <div id="app">发布订阅模式</div>
      <script>
          // 事件触发器
         class EventEmitter {
             // 定义属性，记录所有属性和函数，这个属性是对象
             constructor() {
                //  {'click': [fn1,fn2], 'change': [fn1,fn3,fn4]}
                 this.subs = Object.create(null)
             }
             // 注册事件, eventType 事件类型, hanlder 事件处理函数
             $on (eventType, hanlder) {
                 // 判断eventType是否在subs
                this.subs[eventType] = this.subs[eventType]  || []
                // 把hanlder事件处理函数保存到subs
                this.subs[eventType].push(hanlder)
             }
             // 触发事件
             $emit (eventType) {
                if(this.subs[eventType]) {
                    this.subs[eventType].forEach(hanlder => {
                      hanlder()
                    })
                }
             }
         }

         // 测试
          let  em = new EventEmitter()
          em.$on('click', () =>{
              console.log('click1')
          })
          em.$on('click', () =>{
              console.log('click2')
          })
          em.$emit('click')
      </script>
  </body>
</html>